package com.ywq.wechatordersys.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class HttpAspect {

    //使用日志记录
    private static final Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    @Pointcut("execution(public * com.ywq.wechatordersys.controller.*.*(..))")
    public void log() {


    }

    @Before("log()")
    public void DoBefore(JoinPoint joinPoint) { //这个参数的作用主要是获取方法名和参数


        logger.debug("开始调用方法");

        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //获取请求url
        logger.debug("request_url = {}", request.getRequestURL());
        //获取请求ip地址
        logger.debug("request_ip = {}", request.getRemoteAddr());
        //获取请求方式
        logger.debug("request_method = {}", request.getMethod());
        //获取请求方法名
        logger.debug("request_fun = {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        //获取请求参数
        logger.debug("request_fun = {}", joinPoint.getArgs());

    }

    @After("log()")
    public void DoAfter() {
        logger.debug("结束调用方法");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void DoAfterReturning(Object object) {
        logger.debug("返回结果={}", object.toString());
    }
}
